﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI;
using FreedomERP.Controllers;

namespace FreedomERP.Filter
{
    public class CheckSessionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext httpcontext = HttpContext.Current;
            // 確認目前要求的HttpSessionState
            if (httpcontext.Session != null)
            {
                //確認Session是否為新建立
                if (httpcontext.Session.IsNewSession)
                {
                    //確認是否已存在cookies
                    String sessioncookie = httpcontext.Request.Headers["Cookie"];
                    if ((sessioncookie != null) && (sessioncookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        Logon(filterContext);
                    }
                    else if (HttpContext.Current.Session["user"] == null)
                    {
                        RouteValueDictionary dictionary = new RouteValueDictionary
                        (new
                        {
                            controller = "Account",
                            action = "LogOn",
                            returnUrl = filterContext.HttpContext.Request.RawUrl
                        });
                        filterContext.Result = new RedirectToRouteResult(dictionary);
                    }
                }

            }
            base.OnActionExecuting(filterContext);


        }



        private void Logon(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.StatusCode = 205;
            filterContext.HttpContext.Response.AddHeader("Sessionstatus", "timeout");
            filterContext.Result = new EmptyResult();

        }

    }
}
